
package cz.muni.fi.PA165.musiclibrarybackend.dao;

import cz.muni.fi.PA165.musiclibrarybackend.entities.Album;
import cz.muni.fi.PA165.musiclibrarybackend.entities.IllegalEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author xmacejov
 */
@Repository
public class AlbumDAOImpl implements AlbumDAO, Serializable {

    @PersistenceContext
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    
    public void createAlbum(Album album) {
        if(album == null){
              throw new IllegalArgumentException("album is null");
        }
        if(album.getId() != null){
            throw new IllegalEntityException();
        }
        if(album.getName() == null ){
            throw new IllegalArgumentException();
        }
        entityManager.persist(album);
    }

    public Album getAlbum(Long id) {
        if(id == null){
              throw new IllegalArgumentException("id is null");
        }

        Album album = entityManager.find(Album.class, id);

        return album;
    }

    public List<Album> getAllAlbums() {

        Query query = entityManager.createQuery(
                "SELECT album FROM Album album");

        List<Album> listAlbums = (List<Album>) query.getResultList();

        return listAlbums;
    }

    public void updateAlbum(Album album) {
        if(album == null || album.getId() == null || album.getName() == null){
              throw new IllegalArgumentException("album is null");
        }

        Album found = entityManager.find(Album.class, album.getId());
        
         if (found == null) {
            throw new IllegalEntityException();
         }
         found.setName(album.getName());
         found.setComment(album.getComment());
         found.setAlbumArt(album.getAlbumArt());
         found.setReleaseDate(album.getReleaseDate());
         entityManager.persist(found);
    }

    public void deleteAlbum(Album album) {
        if (album==null){
              throw new IllegalArgumentException("album is null");            
        }
        if (album.getId() == null){
              throw new IllegalArgumentException("album id is null");            
        }

        Album albumToDelete = entityManager.find(Album.class, album.getId());
        
        if (albumToDelete == null){
            throw new IllegalEntityException();
        }
        entityManager.remove(albumToDelete);

    }
    
}
